<template>
  <base-load-page :loadState="false" class="base-load-page">
    <template #head>
      <div style="padding-bottom: 15px" class="head-box">
        <div class="left-box">
          <base-date-picker
            v-model="dataRange"
            valueFormat="YYYY-MM-DD"
            format="YYYY-MM-DD"
            type="daterange"
            startPlaceholder="开始日期"
            endPlaceholder="结束日期"
            style="flex-grow: 0; width: 350px"
            clearable
            @change="getAxiosData(true)"
          ></base-date-picker>
          <base-input-search
            v-model="filterData.referralLinkId"
            clearable
            placeholder="请输入推广链接id"
            style="width: 230px"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
          <base-input-search
            v-model="filterData.thirdAdvertiserId"
            clearable
            placeholder="请输入广告主id"
            style="width: 230px"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
          <base-input-search
            v-model="filterData.dramaTitle"
            clearable
            placeholder="请输入短剧名称"
            style="width: 230px"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
          <bubble-select-local
            v-model="filterData.deptId"
            labelKey="deptName"
            valueKey="deptId"
            :filterable="false"
            style="width: 230px"
            :list="deptListOptions as Record<string, any>[]"
            placeholder="请选择部门"
            @change="getAxiosData(true)"
          ></bubble-select-local>
          <base-input-search
            v-model="filterData.createName"
            clearable
            placeholder="请输入投手名称"
            style="width: 230px"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
          <bubble-select-local
            v-model="filterData.referralLinkType"
            labelKey="label"
            valueKey="value"
            :filterable="false"
            style="width: 230px"
            :list="referralLinkTypeOptionsIaa"
            placeholder="请选择推广链接类型"
            @change="getAxiosData(true)"
          ></bubble-select-local>
          <bubble-select-local
            v-model="filterData.appType"
            labelKey="label"
            valueKey="value"
            :filterable="false"
            style="width: 230px"
            :list="mpPlatformOptions"
            placeholder="小程序平台"
            @change="getAxiosData(true)"
          ></bubble-select-local>
          <base-input-search
            v-model="filterData.thirdAdvertiserName"
            clearable
            placeholder="请输入广告主名称"
            style="width: 230px"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
        </div>
        <div class="right-box">
          <el-button type="success" :icon="EpRefreshRight" :loading="updateAllCorrectPayTotalAmountLoading" @click="updateAllCorrectPayTotalAmountHandler">
            校正充值
          </el-button>
          <el-button type="success" :icon="EpRefreshRight" :loading="syncAllAdvertiserRecordCostLoading" @click="syncAllAdvertiserRecordCostHandler">
            更新消耗
          </el-button>
        </div>
      </div>
    </template>
    <div class="page-content">
      <div class="statistics-block">
        <div v-for="i in statisticsData" :key="i.flag" class="statistics">
          <div class="title">{{ i.name }}</div>
          <div class="value">{{ i.format(censusData) }}</div>
        </div>
        <div class="statistics">
          <div class="title">总时速</div>
          <div class="value">
            <span class="operable" @click="statisticsCommandHandler()">
              {{ censusData ? (censusData?.costHoursSpeed ?? 0) : 0 }}
            </span>
            <span class="operable" style="padding: 0 8px; margin-left: 6px; color: var(--el-color-primary)" @click="toTotalTendency">(趋势)</span>
          </div>
        </div>
      </div>
      <el-table
        ref="elTableRef"
        v-loading="baseData.loading"
        border
        height="100%"
        :data="tableData"
        showOverflowTooltip
        stripe
        style="width: 100%"
        @sort-change="sortChangeHandel"
      >
        <template #empty>
          <base-empty :description="description" :pageLoadButton="[{ text: '重新加载', callBack: () => getAxiosData() }]"></base-empty>
        </template>
        <el-table-column
          fixed
          type="index"
          :index="(index: number) => (filterData.current - 1) * filterData.size + index + 1"
          label="编号"
          sortable
          width="60"
          align="center"
          headerAlign="center"
        ></el-table-column>
        <el-table-column fixed label="投放账户" prop="referralLinkName" minWidth="220">
          <template #default="{ row }">
            <div class="content-wrap">
              <p>
                广告主ID:
                <span class="highlighted" @click="clipboard(row.thirdAdvertiserId)">{{ row.thirdAdvertiserId }}</span>
              </p>
              <p>
                链接ID:
                <span class="highlighted" @click="clipboard(row.referralLinkId)">{{ row.referralLinkId }}</span>
              </p>
              <p>
                <span>{{ row.thirdAdvertiserName || '-' }}</span>
              </p>
            </div>
          </template>
        </el-table-column>
        <el-table-column fixed label="短剧名称" prop="dramaTitle" minWidth="150"></el-table-column>
        <el-table-column fixed label="投手" prop="createName" minWidth="90"></el-table-column>
        <el-table-column label="账户消耗" prop="cost" width="120" sortable="custom">
          <template #default="{ row }">
            <span>{{ formatNumberWithMoney(row.cost) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="时速" prop="costHoursSpeed" minWidth="130" sortable="custom">
          <template #default="{ row }">
            <span style="color: var(--el-color-danger); text-decoration: underline; cursor: pointer" @click="toDataConsumptionSpeed(row)">
              {{ row.costHoursSpeed }}
            </span>
            <span style="margin-left: 6px; color: var(--el-color-primary); text-decoration: underline; cursor: pointer" @click="toTendency(row)">(趋势)</span>
          </template>
        </el-table-column>
        <el-table-column label="新增分成金额" prop="thatdayRegisterDividendAmount" minWidth="140" sortable="custom"></el-table-column>
        <el-table-column label="当日充值分成" minWidth="140" prop="thatdayDividendAmount" sortable="custom">
          <template #default="{ row }">
            <span>{{ formatNumberWithMoney(row.thatdayDividendAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="新增广告分成" prop="iaaRegisterDividendAmount" minWidth="150" sortable="custom">
          <template #default="{ row }">
            <span>{{ formatNumberWithMoney(row.iaaRegisterDividendAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="当日广告分成" prop="iaaDividendAmount" minWidth="150" sortable="custom">
          <template #default="{ row }">
            <span>{{ formatNumberWithMoney(row.iaaDividendAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="利润" prop="thatdayProfitAmount" minWidth="100" sortable="custom">
          <template #default="{ row }">
            <span>{{ formatNumberWithMoney(row.thatdayProfitAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="回本率" prop="extRecoveryRate" minWidth="120">
          <template #default="{ row }">
            <span>{{ row.extRecoveryRate }}%</span>
          </template>
        </el-table-column>
        <el-table-column label="千展成本" prop="avgShowCost" width="120" sortable="custom"></el-table-column>
        <el-table-column label="展示数" prop="show" width="100" sortable="custom"></el-table-column>
        <el-table-column label="点击数" prop="click" width="100" sortable="custom"></el-table-column>
        <el-table-column label="点击成本" prop="avgClickCost" width="110" sortable="custom"></el-table-column>
        <el-table-column label="点击率" prop="ctr" width="100" sortable="custom" :formatter="(row) => `${row.ctr}%`"></el-table-column>
        <el-table-column label="转化数" prop="convert" minWidth="100" sortable="custom"></el-table-column>
        <el-table-column label="转化成本" prop="convertCost" minWidth="110" sortable="custom"></el-table-column>
        <el-table-column label="转化率" prop="convertRate" minWidth="110" sortable="custom" :formatter="(row) => `${row.convertRate}%`"></el-table-column>
        <el-table-column label="付费人数" prop="thatdayPaidUseNum" minWidth="110" sortable="custom"></el-table-column>
        <el-table-column label="付费次数" prop="thatdayPaidTotalNum" minWidth="110" sortable="custom"></el-table-column>
        <el-table-column label="付费成本" prop="extPayCost" minWidth="110">
          <template #default="{ row }">
            <span>{{ row.extPayCost }}</span>
          </template>
        </el-table-column>
        <el-table-column label="客单价" prop="extAvgPrice" minWidth="110">
          <template #default="{ row }">
            <span>{{ row.extAvgPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column label="回传率" prop="" minWidth="90">
          <template #default="{ row }">
            <span>{{ convertToPercentage(row.convert, row.thatdayPaidUseNum) }}</span>
          </template>
        </el-table-column>
        <el-table-column sortable fixed="right" label="操作" width="100" align="center" headerAlign="center">
          <template #default="{ row, $index }">
            <div style="display: flex; flex-direction: column; gap: 4px; overflow: hidden">
              <el-button
                link
                type="primary"
                size="small"
                :loading="row._syncAdvertiserRecordCostLoading"
                style="margin-left: 0"
                :icon="EpMostlyCloudy"
                @click="syncAdvertiserRecordCostHandler(row)"
              >
                校正消耗
              </el-button>
              <el-button
                link
                type="primary"
                size="small"
                :loading="row._correctionDataLoading"
                style="margin-left: 0"
                :icon="EpMostlyCloudy"
                @click="handleCorrectionData(row, $index)"
              >
                校正充值
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="新增充值" prop="thatdayRegisterTotalAmount" minWidth="110" sortable="custom"></el-table-column>
        <el-table-column label="当日充值" prop="thatdayTotalAmount" minWidth="110" sortable="custom">
          <template #default="{ row }">
            <span>{{ formatNumberWithMoney(row.thatdayTotalAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="新增广告收益" prop="iaaRegisterTotalAmount" minWidth="140" sortable="custom">
          <template #default="{ row }">
            <span>{{ formatNumberWithMoney(row.iaaRegisterTotalAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="当日广告收益" prop="iaaTotalAmount" minWidth="140" sortable="custom">
          <template #default="{ row }">
            <span>{{ formatNumberWithMoney(row.iaaTotalAmount) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <template #foot>
      <div class="pagination-box">
        <el-pagination
          v-model:currentPage="filterData.current"
          v-model:pageSize="filterData.size"
          :pageSizes="[20, 30, 40, 50]"
          :disabled="baseData.loading"
          :pagerCount="13"
          layout="total, prev, pager, next, sizes, jumper"
          :total="baseData.total"
          @change="getAxiosData(true)"
        ></el-pagination>
      </div>
    </template>
    <data-consumption-speed ref="dataConsumptionSpeedRef"></data-consumption-speed>
    <data-consumption-speed-all ref="dataConsumptionSpeedAllRef"></data-consumption-speed-all>
    <tendency-dialog ref="tendencyDialogRef"></tendency-dialog>
  </base-load-page>
</template>

<script setup lang="ts">
  import IconSearch from '~icons/ep/search';
  import EpMostlyCloudy from '~icons/ep/mostly-cloudy';
  import EpRefreshRight from '~icons/ep/refresh-right';
  import {
    type GetPageEverydayConsumeRequest,
    type OceAdvertiserEverydayCostItem,
    type OceEverydayCostCensusData,
    correctPayTotalAmount,
    getOceEverydayCostCensusData,
    getPageEverydayConsumeJl,
    syncAdvertiserRecordCost,
    syncAllAdvertiserRecordCost,
    updateAllCorrectPayTotalAmount,
  } from '@/api/marketing-management';
  import { convertToPercentage, formatNumberWithMoney } from '@/utils/numb';
  import DataConsumptionSpeed from './components/data-consumption-speed.vue';
  import DataConsumptionSpeedAll from './components/data-consumption-speed-all.vue';
  import { useClipboard } from '@vueuse/core';
  import TendencyDialog from './components/tendency-dialog.vue';
  import { confirmThePromptTwice } from '@/utils/common.ts';
  import { mpPlatformOptions, referralLinkTypeOptionsIaa } from '@/views/app-main/marketing-management/selectorOptions.ts';
  import { type DeptItem, getSysDeptListAxios } from '@/api/permission-management.ts';
  const { copy, isSupported } = useClipboard({ legacy: true });

  const { proxy } = getCurrentInstance() as any;
  const route = useRoute();
  const elTableRef: $RefComp<'ElTable'> = ref(null);
  const baseData = shallowReactive({
    type: 'add' as 'add' | 'edit',
    /** 加载状态 */
    loading: true,
    /** 总数量 */
    total: 0,
  });
  const deptListOptions: Ref<DeptItem[]> = ref([]);
  const dataRange = ref<[string, string] | undefined>();
  const filterData = ref<GetPageEverydayConsumeRequest>({
    current: 1,
    size: 40,
    iaaFlag: 1,
    startDate: '',
    appType: '',
    endDate: '',
    dramaTitle: '',
    createName: '',
    referralLinkId: '',
    referralLinkType: '',
    thirdAdvertiserId: '',
    column: 'cost',
    thirdAdvertiserName: '',
    deptId: undefined,
    asc: false,
  });

  watch(
    () => dataRange.value,
    (val) => {
      if (Array.isArray(val) && val.length >= 2) {
        filterData.value.startDate = val[0];
        filterData.value.endDate = val[1];
      } else {
        filterData.value.startDate = '';
        filterData.value.endDate = '';
      }
    }
  );

  const censusData = ref<OceEverydayCostCensusData>({
    cost: null,
    thatdayPaidTotalNum: null,
    thatdayProfitAmount: null,
    thatdayTotalAmount: null,
  });

  type _TableDataRow = OceAdvertiserEverydayCostItem & {
    _correctionDataLoading?: boolean;
    _syncAdvertiserRecordCostLoading?: boolean;
  };

  const tableData: Ref<_TableDataRow[]> = ref([]);
  const description = ref('');
  const syncAllAdvertiserRecordCostLoading = ref(false);
  const updateAllCorrectPayTotalAmountLoading = ref(false);

  const dataConsumptionSpeedRef = ref<InstanceType<typeof DataConsumptionSpeed>>();
  const dataConsumptionSpeedAllRef = ref<InstanceType<typeof DataConsumptionSpeedAll>>();
  const tendencyDialogRef = ref<InstanceType<typeof TendencyDialog>>();

  /** 跳转时速列表 */
  function toDataConsumptionSpeed(item: OceAdvertiserEverydayCostItem) {
    dataConsumptionSpeedRef.value?.show({
      thatdayTimestamp: item.thatdayTimestamp!,
      referralLinkId: item.referralLinkId!,
    });
  }

  /** 部门列表 */
  function handleGetSysDeptListAxios() {
    getSysDeptListAxios({}).then((res) => {
      deptListOptions.value = res.data;
    });
  }
  onMounted(() => {
    // filterData.value.currentDate = proxy.$dayjs().format('YYYY-MM-DD');
    filterData.value.referralLinkId = (route.query.referralLinkId as string) ?? '';
    dataRange.value = [proxy.$dayjs().format('YYYY-MM-DD'), proxy.$dayjs().format('YYYY-MM-DD')];
    getAxiosData();
    handleGetSysDeptListAxios();
  });

  /** 重置 */
  function initPageData() {
    tableData.value = [];
  }

  /** 校正金额 */
  async function handleCorrectionData(row: _TableDataRow, idx: number) {
    try {
      row._correctionDataLoading = true;
      const { data } = await correctPayTotalAmount({ advertiserCostId: row.advertiserCostId! });
      row._correctionDataLoading = false;
      tableData.value.splice(idx, 1, data);
      ElToast.success('校正成功');
      getAxiosData(false);
    } catch (error) {
      row._correctionDataLoading = false;
      ElToast.error(error.msg || `校正失败，-BD004`);
    }
  }

  /** 校正消耗 */
  async function syncAdvertiserRecordCostHandler(row: _TableDataRow) {
    try {
      row._syncAdvertiserRecordCostLoading = true;
      await syncAdvertiserRecordCost({ advertiserCostId: row.advertiserCostId! });
      row._syncAdvertiserRecordCostLoading = false;
      ElToast.success('校正成功');
      getAxiosData(false);
    } catch (error) {
      row._syncAdvertiserRecordCostLoading = false;
      ElToast.error(error.msg || `校正失败，-BD004`);
    }
  }

  /** 校正消耗 */
  function syncAllAdvertiserRecordCostHandler() {
    confirmThePromptTwice(async () => {
      try {
        syncAllAdvertiserRecordCostLoading.value = true;
        await syncAllAdvertiserRecordCost({ startDate: filterData.value.startDate, endDate: filterData.value.endDate, iaaFlag: 1 });
        syncAllAdvertiserRecordCostLoading.value = false;
        ElToast.success('校正成功');
        getAxiosData(false);
      } catch (error) {
        syncAllAdvertiserRecordCostLoading.value = false;
        ElToast.error(error.msg || `校正失败，-BD004`);
      }
    }, '此操作会重新全量同步数据,同步时间较长,确定继续吗?');
  }

  /** 校正充值 */
  function updateAllCorrectPayTotalAmountHandler() {
    confirmThePromptTwice(async () => {
      try {
        updateAllCorrectPayTotalAmountLoading.value = true;
        await updateAllCorrectPayTotalAmount({ startDate: filterData.value.startDate, endDate: filterData.value.endDate, iaaFlag: 1 });
        updateAllCorrectPayTotalAmountLoading.value = false;
        ElToast.success('校正成功');
        getAxiosData(false);
      } catch (error) {
        updateAllCorrectPayTotalAmountLoading.value = false;
        ElToast.error(error.msg || `校正失败，-BD004`);
      }
    }, '此操作会重新全量同步数据,同步时间较长,确定继续吗?');
  }

  /**
   * 设置表格数据
   */
  async function getAxiosData(showLoading = true) {
    try {
      await nextTick();
      baseData.loading = Boolean(showLoading);

      const res = await Promise.all([getPageEverydayConsumeJl(filterData.value), getOceEverydayCostCensusData(filterData.value)]);
      censusData.value = res[1].data;

      if (res[0].data.records.length > 0) {
        tableData.value = res[0].data.records;
        filterData.value.current = res[0].data.current;
        filterData.value.size = res[0].data.size;
        baseData.total = res[0].data.total;
      } else {
        description.value = '暂无数据';
        initPageData();
      }
      baseData.loading = false;
    } catch (error) {
      baseData.loading = false;
      initPageData();
      description.value = error.msg || '加载失败，-BD001';
    }
  }

  const sortProps = [
    'cost',
    'costHoursSpeed',
    'thatdayTotalAmount',
    'thatdayDividendAmount',
    'thatdayProfitAmount',
    'avgShowCost',
    'show',
    'click',
    'avgClickCost',
    'ctr',
    'convert',
    'convertCost',
    'convertRate',
    'thatdayPaidUseNum',
    'thatdayPaidTotalNum',
    'thatdayRegisterDividendAmount',
    'thatdayRegisterTotalAmount',
    'iaaDividendAmount',
    'iaaTotalAmount',
    'iaaRegisterTotalAmount',
    'iaaRegisterDividendAmount',
    'extRecoveryRate',
    'extPayCost',
    'extAvgPrice',
  ];

  const humpToSnake = (str: string) => {
    return str.replace(/([A-Z])/g, '_$1').toLowerCase();
  };

  /** 表格列排序 */
  const sortChangeHandel = ({ prop, order }: { prop: string; order: 'ascending' | 'descending' | null }) => {
    if (sortProps.includes(prop)) {
      filterData.value.column = ['show', 'convert'].includes(prop) ? `\`${prop}\`` : humpToSnake(prop);
      if (order === 'ascending') {
        filterData.value.asc = true;
      } else if (order === 'descending') {
        filterData.value.asc = false;
      } else {
        filterData.value.column = 'cost';
        filterData.value.asc = false;
      }
      getAxiosData(true);
    } else {
      filterData.value.column = 'cost';
      filterData.value.asc = false;
    }
  };

  interface StatisticsItem {
    name: string;
    flag: keyof OceEverydayCostCensusData;
    type?: string;
    format: (val: OceEverydayCostCensusData) => number | string;
  }

  const statisticsData = ref<StatisticsItem[]>([
    {
      name: '总消耗金额',
      flag: 'cost',
      format(val) {
        return formatNumberWithMoney(val?.cost) ?? 0;
      },
    },
    {
      name: '总支付笔数',
      flag: 'thatdayPaidTotalNum',
      format(val) {
        return val?.thatdayPaidTotalNum ?? 0;
      },
    },
    {
      name: '总收入',
      flag: 'thatdayTotalAmount',
      format(val) {
        return formatNumberWithMoney(val?.thatdayTotalAmount || 0) ?? 0;
      },
    },
    {
      name: '总分成金额',
      flag: 'thatdayDividendAmount',
      format(val) {
        return formatNumberWithMoney(val?.thatdayDividendAmount || 0) ?? 0;
      },
    },
    {
      name: '广告总收入',
      flag: 'iaaTotalAmount',
      format(val) {
        return formatNumberWithMoney(val?.iaaTotalAmount || 0) ?? 0;
      },
    },
    {
      name: '广告总分成金额',
      flag: 'iaaDividendAmount',
      format(val) {
        return formatNumberWithMoney(val?.iaaDividendAmount || 0) ?? 0;
      },
    },
    {
      name: '新增广告总收益',
      flag: 'iaaRegisterTotalAmount',
      format(val) {
        return formatNumberWithMoney(val?.iaaRegisterTotalAmount || 0) ?? 0;
      },
    },
    {
      name: '总利润',
      flag: 'thatdayProfitAmount',
      format(val) {
        return formatNumberWithMoney(val?.thatdayProfitAmount || 0) ?? 0;
      },
    },
    {
      name: '回本率',
      flag: 'roic',
      format(val) {
        return `${val?.extRecoveryRate ?? 0}%`;
      },
    },
  ]);
  /** 查询某小时总消耗列表 - 分页 */
  function statisticsCommandHandler() {
    dataConsumptionSpeedAllRef.value?.show({
      filterData: filterData.value,
    });
  }

  /** 打开趋势 (表格内的) */
  function toTendency(row: OceAdvertiserEverydayCostItem) {
    tendencyDialogRef.value?.show({
      type: 'row',
      /** 推广链接id */
      referralLinkId: row.referralLinkId!,
      /** 当日日期时间戳 */
      thatdayTimestamp: row.thatdayTimestamp!,
    });
  }

  /** 打开趋势 (总数据) */
  function toTotalTendency() {
    tendencyDialogRef.value?.show({
      type: 'total',
      /** 当日日期时间戳 */
      startDate: filterData.value.startDate!,
      /** 当日日期时间戳 */
      endDate: filterData.value.endDate!,
      filterData: filterData.value,
    });
  }

  /** 复制 */
  async function clipboard(text: string) {
    if (!isSupported) {
      ElToast.error('您的浏览器不支持复制');
    } else {
      try {
        await copy(text);
        ElToast.success('复制成功');
      } catch (error) {
        ElToast.error('复制失败');
      }
    }
  }
</script>

<style lang="scss" scoped>
  .pagination-box {
    @include flex(row, nowrap, center, center, center);
    padding-top: 15px;
  }

  .head-box {
    @include flex(row, nowrap, flex-start, center, center);
    align-items: start;

    .left-box {
      // display: grid;
      display: flex;
      flex: 1;
      flex-wrap: wrap;
      // grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
      // grid-gap: 15px;
      gap: 14px;
      margin-right: 15px;
    }
  }

  .page-content {
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .content-wrap {
    white-space: wrap;
  }
</style>
